<?php
/**
 *Create by PhpStorm
 *User:Kendy
 *Date:2019/10/8/008
 *Time:14:19
 */
namespace app\common\model;
use think\Model;
use think\Db;
use app\common\model\UserModel as um;
use app\common\model\HotelOrderListModel as hol;
use app\common\model\LogOrderModel as lo;
class hotelOrderModel extends Model
{
    // 确定链接表名
    protected $name = 'hotel_order';

    /**
     * 根据搜索条件获取所有的酒店订单数据
     * @param $where  查询条件
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function getHotelOrderList($where ,$offset, $limit)
    {
        $resultData = $this
            ->alias('ho')
            ->join('hotel h','ho.hotel_id=h.hotel_id','left')
            ->join('hotel_room hr','hr.room_id=ho.room_id','left')
            ->where($where)
            ->field('h.hotel_name,ho.commission_fee,ho.procedure_fee,hr.room_name,h.hotel_tel,ho.order_id,ho.order_sn,ho.hotel_id,ho.room_id,ho.uid,ho.linkman,ho.tel,ho.start_time,
            ho.end_time,ho.living_days,room_amount,ho.living_peason,ho.content,ho.order_status,ho.total_price,ho.coupon_id,
            ho.coupon_price,ho.order_price,ho.pay_type,ho.is_pay,ho.cancel_id,ho.is_appraise,ho.is_refund,ho.order_unique,ho.is_del,ho.create_time')
            ->order('order_id desc')
            ->limit($offset, $limit)
            ->select();
        if(count($resultData)>0)
        {
              foreach ($resultData as $key => $v)
              {
                  $resultData[$key]['order_status'] = lvOrderStatus($v['order_status']);
				          $resultData[$key]['pay_type'] = lvPayType($v['pay_type']);
                  $resultData[$key]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
              }
        }
        return $resultData;
    }


    /**
     * 根据搜索条件获取所有的酒店订单数量
     * @param $where  查询条件
     * @return mixed
     */
    public function  getHotelOrderCount($where)
    {
        return $this
            ->alias('ho')
            ->join('hotel h','ho.hotel_id=h.hotel_id','left')
            ->join('hotel_room hr','hr.room_id=ho.room_id','left')
            ->where($where)
            ->count();
    }

    /**根据搜索条件获取单条的酒店订单信息
     * @param $where 查询条件
     * @return mixed
     */
    public function  getHotelOrderById($where)
    {
        $resultData = $this
            ->alias('ho')
            ->join('hotel h','ho.hotel_id=h.hotel_id','left')
            ->join('hotel_room hr','hr.room_id=ho.room_id','left')
            ->where($where)
            ->field('h.hotel_name,hr.room_name,h.hotel_tel,ho.order_id,ho.order_sn,ho.hotel_id,ho.room_id,ho.uid,ho.linkman,ho.tel,ho.start_time,
            ho.end_time,ho.living_days,ho.living_peason,ho.content,ho.order_status,ho.total_price,ho.coupon_id,
            ho.coupon_price,ho.order_price,ho.pay_type,ho.is_pay,ho.cancel_id,ho.is_appraise,ho.is_refund,ho.order_unique,ho.is_del,ho.create_time')
            ->find();
        if(empty($resultData)) return [];
        $nameObj = Db::name('hotel_orderlist')->where($where)->select();
        foreach ($nameObj as $k => $v) {
          $nameArr[] = $v['username'];
        }
        $resultData['linkman'] = implode(' , ', $nameArr);
        $resultData['pay_type'] = lvPayType($resultData['pay_type']);
        $resultData['order_status'] = lvOrderStatus($resultData['order_status']);
        $resultData['create_time'] = date('Y-m-d H:i:s',$resultData['create_time']);
        $resultData['start_time'] = date('Y-m-d',$resultData['start_time']);
        $resultData['end_time'] = date('Y-m-d',$resultData['end_time']);
        $userInfo = new um;
        $resultData['username'] = $userInfo->getUserInfoById(['uid'=>$resultData['uid']])['nickname'];
        return $resultData;
    }

    public function submitHotelOrder()
    { 
      $room_id = input('post.room_id');
       if(empty($room_id))
       return apiReturn('400','房间id为空',0);
      $linkman = input('post.linkman/s');
      if(empty($linkman))
       return apiReturn('400','入住人信息为空',0);
      $room_amount = input('post.room_amount');
      if(empty($room_amount))
       return apiReturn('400','预定的房间数量为空',0);
      $tel = input('post.tel');
      if(empty($tel))
       return apiReturn('400','手机号为空',0); 
       $uid = input('post.uid');
      if(empty($uid))
       return apiReturn('400','用户信息为空',0);
       $start_time = input('post.start_time');
       if(empty($start_time))
       return apiReturn('400','开始时间为空',0);  
       $end_time = input('post.end_time');
       if(empty($end_time))
       return apiReturn('400','结束时间为空',0);   //living_days living_peason 
       $content = input('post.content');  
       //查看是否有房间信息
       $roomInfo = Db::name('hotel_room')
       ->alias('hr')
       ->field('hr.is_tehui,hr.room_discount_price,hr.room_id,hr.room_price,hr.hotel_id,hr.room_name,h.hotel_name,h.hotel_tel')
       ->join('hotel h','h.hotel_id=hr.hotel_id','left')
       ->where(['hr.is_del'=>0,'hr.is_display'=>0,'hr.room_id'=>$room_id,'h.is_del'=>0,'is_pass'=>1])
       ->find();
       if(empty($roomInfo))
        return apiReturn('400','房间信息无效',0);
       $linkmanArr = explode(',', $linkman);
       $living_peason = count($linkmanArr);
       //计算订单价格
       if($roomInfo['is_tehui']) $order_price = $roomInfo['room_discount_price'];
       else  $order_price = $roomInfo['room_price'];
       //计算入住几天
       $living_days =  diffBetweenTwoDays($start_time,$end_time);
       //返回给前段的数据
       $returnData['room_id'] = $room_id;
       $returnData['hotel_name'] = $roomInfo['hotel_name'];
       $returnData['room_name'] = $roomInfo['room_name'];
       $returnData['start_time'] =  $start_time;
       $returnData['end_time'] =  $end_time;
       $returnData['room_amount'] = $room_amount;
       $returnData['order_price'] = $order_price * $room_amount * $living_days;
       //生成订单
       Db::startTrans();
       try{
        $orderSn = makeOrderSn(); 
        //计算该酒店的订单佣金
        $commissionRate = Db::name('hotel') 
        ->where(['is_del'=>0,'is_pass'=>1,'hotel_id'=>$roomInfo['hotel_id']])
        ->value("commission_rate");
        if(empty($commissionRate))
        $commissionRate = 0;  

        //创建订单
        $order['order_sn']  = $orderSn;
        $order['hotel_id'] = $roomInfo['hotel_id'];
        $order['room_id'] = $roomInfo['room_id'];
        $order['room_name'] = $roomInfo['room_name'];
        $order['uid'] = $uid;
        $order['linkman'] = $linkmanArr[0];
        $order['tel'] = $tel;
        $order['start_time'] = strtotime($start_time);
        $order['end_time'] = strtotime($end_time);
        $order['order_price'] = $order_price * $room_amount * $living_days;
        $order['total_price'] = $order_price;
        $order['living_days'] = $living_days; 
        $order['room_amount'] = $room_amount;
        $order['living_peason'] = $living_peason; 
        $order['create_time'] = time(); 
        $order['content'] = $content; 
        $order['commission_rate'] =  $commissionRate; 
        $order['cancel_code'] = 'hotel_cancle_code_'.getRandNumber();
        $result = $this->isUpdate(false)->save($order);
         $returnData['room_id'] = $orderSn;
        if(false !== $result)
        {
           $orderId = $this->order_id; 
           // 订单拆分 hotel_orderlist用户信息 
           $orderListModel = new hol();
           $orderListModel->makeOrderList($linkmanArr, $orderId,$roomInfo['hotel_id']);
             //创建订单记录 
            $logOrder = new lo();
            $logOrder->addLogOrder($orderId,1, $uid, 0, '下单成功，等待用户付');
            //给用户发送消息提示 1景点订单 2酒店订单 3旅行社订单
            send_user_message(2, 2, $uid, $orderSn,$roomInfo['room_name'],$orderId,2);
            
           }
        Db::commit();
        return apiReturn('200','提交订单成功',$returnData);  
       }catch(\Exection $e)
       { 
        Db::rollback();
        return apiReturn('400','提交订单失败',0); 
       }
       

    }  

}